<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 文件操作接口
 */
class API extends MY_Controller{

	//根目录
	private $basepath;

	//配置
	private $attrcofig;

	//输出给前台的配置
	private $fconfig;

	//参数
	private $get;
	private $json;
	private $result;

	private $plugindir;

	private $error;

	private $uploadData;

	function __construct(){
		parent::__construct();
		$this->plugindir = FCPATH.'public/tinymce/plugins/moxiemanager/';
		$this->attrconfig = $this->Cache_model->loadConfig('attr');
		$this->basepath='data/attachment/'.$this->attrconfig['userfolder'].'/'.$this->member->mname;
		$this->fconfig = array(
				"general.hidden_tools"=>"",
				"general.disabled_tools"=>"",
				"filesystem.extensions"=>"*",
				"filesystem.force_directory_template"=>false,
				"upload.maxsize"=>"2MB",
				"upload.chunk_size"=>"5mb",
				"upload.extensions"=>"*",
				"createdoc.templates"=>"",
				//"Index page=/testfiles/templates/document.htm,Normal page=/testfiles/templates/another_document.htm",
				"createdoc.fields"=>"Document title=title",
				"createdir.templates"=>""
				//"Image folder=/testfiles/templates/directory"
				);
	}

	public function index(){
		$this->needLogin();

		$this->get=$this->input->get(NULL,TRUE);
		$this->json=json_decode($this->input->post('json'),TRUE);
		$this->result=array('jsonrpc'=>'2.0');

		if(!empty($this->json) && isset($this->json['id'])){
			$result['id']=$this->json['id'];
		}

		switch ($this->get['action']) {
			case 'upload':
				if($this->upload()){
					//上传成功返回
					$this->result['files']=$this->uploadData;
				}else{
					$this->result['error']=array(
					"code"=>100,
					"message"=>empty($this->error)?'上传错误':$this->error,
					"data"=>null
					);
				}
				break;
			case 'language':
				echo file_get_contents($this->plugindir.'langs/zh_CN.js');
				echo file_get_contents($this->plugindir.'langs/moxman_zh_CN.js');
				exit;
			case 'PluginJs':
				echo file_get_contents($this->plugindir.'js/Plugin.js');
				exit;
			case 'streamfile':
				//预览
				//action=streamfile&path=%2Ftestfiles%2Fcamera.jpg&u=70567

				//编辑
				//action=streamfile&stream=true&path=%2Ftestfiles%2Fcamera.jpg&r=1392432702925
				exit;
			case 'download':
				//下载
				//action=download&path=/testfiles&names=moreimages,camera.jpg&zipname=files.zip
				exit;
			default:
				switch ($this->json['method']) {
					case 'listRoots':
						$this->listRoots();
						break;
					case 'listFiles':
						$this->listFiles();
						break;
					case 'FileInfo':
						$this->FileInfo();
						break;
					case 'getConfig':
						$this->getConfig();
						break;
					case 'createDirectory':
						$this->createDirectory();
						break;
					case 'createDocument':
						$this->createDocument();
						break;
					case 'loopback':
						# code...
						break;
					case 'moveTo':
						$this->moveTo();
						break;
					case 'favorites.add':
						break;
					case 'zip':
						$this->zip();
						break;
					case 'delete':
						$this->delete();
						break;
					default:
						$this->error(100,'未定义操作');
						break;
				}

				break;
		}

		echo json_encode($this->result);
	}

	//头像上传
	public function avatar(){
		$save_path = $this->basepath.'/';
		if (!file_exists($save_path)) {
			mkdir($save_path);
		}
		$uploadconfig['upload_path'] = $save_path;
		$uploadconfig['allowed_types'] = 'jpg|png|gif';
		$uploadconfig['max_size'] = $this->attrconfig['attr_maxsize']?$this->attrconfig['attr_maxsize']:0;
		$uploadconfig['encrypt_name']  = TRUE;
		$uploadconfig['remove_spaces']  = TRUE;
		$uploadconfig['overwrite']=TRUE;
		$uploadconfig['file_name']='avatar';
		$this->load->library('upload', $uploadconfig);
		if(!$this->upload->do_upload('avatar')){
			//$result = array('error'=>1,'message'=>$this->upload->display_errors('',''));
			$this->showMessage('上传失败',$this->upload->display_errors('',''),site_url('member/avatar'));
		}else{
			$data = $this->upload->data();
			$this->Data_model->editData(array('mid'=>$this->member->mid,),array('avatar'=>'/'.$save_path.$data['file_name']),'member');
			//$result = array('error'=>0,'url'=>base_url($save_path.$data['file_name']));
			$this->showMessage('上传成功','头像已经成功上传！',site_url('member/avatar'));
		}

	}

	//{"jsonrpc":"2.0","error":{"code":100,"message":"This action is restricted in demo mode.","data":null},"id":"i3"}
	private function error($code,$message,$data=NULL){
		$this->result['error']=array(
			'code'=>$code,
			'message'=>$message,
			'data'=>$data
			);
		echo json_encode($this->result);
		exit;
	}

	private function listRoots(){
		$this->result['result']=array(
			array(
			'name'=>basename($this->basepath),
			'path'=>'/'.basename($this->basepath),
			"meta"=>array("standalone"=>"false"),
			'config'=>$this->fconfig
			)
		);
	}
	
	private function listFiles(){
		$param=$this->json['params'];
		$folder=$param['path'];
		$files=array();
		$dir=rtrim(dirname($this->basepath).$folder,'/');
		if(is_dir($dir)){
			$fd=opendir($dir);
			while(($file = readdir($fd)) !== FALSE){
				if($file=='.' || $file=='..')continue;
				$files[]=array(
					$file,
					filesize($dir.'/'.$file),
					filemtime($dir.'/'.$file),
					$this->filemod(fileperms($dir.'/'.$file)),
					array()
					);
			}
			closedir($fd);
		}
		$this->result['result']=array(
			'columns'=>array("name","size","modified","attrs","info"),
			'config'=>$this->fconfig,
			'file'=>array(
				"path"=>$folder,
				"size"=>4096,
				"lastModified"=>filemtime($dir),
				"isFile"=>false,
				"canRead"=>true,
				"canWrite"=>true,
				"canEdit"=>false,
				"canRename"=>true,
				"canView"=>false,
				"canPreview"=>false,
				"exists"=>true,
				"meta"=>array("url"=>site_url().$dir)
				),
			'urlFile'=>NULL,
			'data'=>$files,
			'url'=>site_url().$dir,
			"thumbnailFolder"=>"",
			"thumbnailPrefix"=>"",
			"offset"=>18,
			"last"=>true
			);
	}

	private function FileInfo(){
		$param=$this->json['params'];
		if(isset($param['path'])){
			$file=$param['path'];
			$dir=dirname($this->basepath).$file;
			$this->result['result']=array(
				"path"=>$file,
				"size"=>filesize($dir),
				"lastModified"=>filemtime($dir),
				"isFile"=>false,
				"canRead"=>true,
				"canWrite"=>true,
				"canEdit"=>false,
				"canRename"=>true,
				"canView"=>false,
				"canPreview"=>false,
				"exists"=>true,
				"meta"=>array("url"=>site_url().$dir),
				"info"=>array()
				);
		}elseif(isset($param['paths'])){
			foreach ($param['paths'] as $key => $value) {
				$file=$value;
				$dir=dirname($this->basepath).$file;
				$this->result['result'][]=array(
					"path"=>$file,
					"size"=>filesize($dir),
					"lastModified"=>filemtime($dir),
					"isFile"=>false,
					"canRead"=>true,
					"canWrite"=>true,
					"canEdit"=>false,
					"canRename"=>true,
					"canView"=>false,
					"canPreview"=>false,
					"exists"=>true,
					"meta"=>array("url"=>site_url().$dir),
					"info"=>array()
					);
			}
		}
	}
	
	private function getConfig(){
		$this->result['result']=$this->fconfig;
	}
	
	private function createDirectory(){

	}
	
	private function createDocument(){

	}
	
	private function moveTo(){

	}
	
	private function zip(){

	}
	
	private function delete(){

	}
	
	//?action=upload&path=%2Ftestfiles&name=avatar.jpg&loaded=0&total=36405&id=null
	private function upload(){
		/*$usergroupid=$this->session->userdata('usergroup');
		if(!$usergroupid){
			$result = array('error'=>1,'message'=>lang('nopur'));
			echo json_encode($result);exit;
		}*/
		$save_path = $this->basepath;
		$ext_arr = array(
				'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
				'flash' => array('swf', 'flv'),
				'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'rm', 'rmvb'),
				'file' => array('gif', 'jpg', 'jpeg', 'png', 'bmp','doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
		);
		
		$dir_name = $this->get['path'];
		if(strpos($dir_name, '..')){
			$this->error='目录请求错误';
			return FALSE;
		}
		if(!(strpos($dir_name, '/'.$this->member->mname.'/')===0 ||
			$dir_name == '/'.$this->member->mname)){
			$this->error='目录请求错误';
			return FALSE;
		}
		/*if(!in_array($dir_name,array('image','flash','media','file'))){
			$this->error="Invalid Directory name.";
			return FALSE;
		}*/
		$save_path = dirname($save_path).$dir_name.'/';
		if (!file_exists($save_path)) {
				mkdir($save_path);
		}
		/*$save_path .= date('Ymd').'/';
		if (!file_exists($save_path)) {
			mkdir($save_path);
		}*/

		$filename=$this->get['name'];
		$fileinfo=pathinfo($filename);
		$pass=false;
		foreach ($ext_arr as $key => $value) {
			if(in_array(strtolower($fileinfo['extension']),$value)){
				$pass=TRUE;
				break;
			}
			//$uploadconfig['allowed_types'] .= implode('|',$value);
		}
		if(!$pass){
			$this->error='不允许上传的文件类型';
			return FALSE;
		}

		$filename =  $fileinfo['filename'].'.'.strtolower($fileinfo['extension']);
		$i=1;
		while(file_exists($save_path.$filename)){
			$filename=$fileinfo['filename'].'-'.($i++).'.'.strtolower($fileinfo['extension']);
		}
		$uploadconfig['allowed_types'] = '*';
		//$uploadconfig['allowed_types'] = implode('|',$ext_arr[$dir_name]);
		$uploadconfig['upload_path'] = $save_path;
		$uploadconfig['max_size'] = $this->attrconfig['attr_maxsize']?$this->attrconfig['attr_maxsize']:0;
		$uploadconfig['encrypt_name']  = TRUE;
		$uploadconfig['remove_spaces']  = TRUE;
		$uploadconfig['overwrite']=TRUE;
		$uploadconfig['file_name']=$filename;
		$this->load->library('upload', $uploadconfig);
		if(!$this->upload->do_upload('file')){
			$this->error=$this->upload->display_errors('','');
			return FALSE;
			//$result = array('error'=>1,'message'=>$this->upload->display_errors('',''));
		}else{
			$this->uploadData = $this->upload->data();
			
			return TRUE;
			//$result = array('error'=>0,'url'=>base_url($save_path.$data['file_name']));
		}
		//echo json_encode($result);
	}

	private function filemod($perms){
		//$perms = fileperms('/etc/passwd');

		if (($perms & 0xC000) == 0xC000) {
		    // Socket
		    $info = 's';
		} elseif (($perms & 0xA000) == 0xA000) {
		    // Symbolic Link
		    $info = 'l';
		} elseif (($perms & 0x8000) == 0x8000) {
		    // Regular
		    $info = '-';
		} elseif (($perms & 0x6000) == 0x6000) {
		    // Block special
		    $info = 'b';
		} elseif (($perms & 0x4000) == 0x4000) {
		    // Directory
		    $info = 'd';
		} elseif (($perms & 0x2000) == 0x2000) {
		    // Character special
		    $info = 'c';
		} elseif (($perms & 0x1000) == 0x1000) {
		    // FIFO pipe
		    $info = 'p';
		} else {
		    // Unknown
		    $info = 'u';
		}

		// Owner
		$info .= (($perms & 0x0100) ? 'r' : '-');
		$info .= (($perms & 0x0080) ? 'w' : '-');
		$info .= (($perms & 0x0040) ?
		            (($perms & 0x0800) ? 's' : 'x' ) :
		            (($perms & 0x0800) ? 'S' : '-'));

		// Group
		$info .= (($perms & 0x0020) ? 'r' : '-');
		$info .= (($perms & 0x0010) ? 'w' : '-');
		$info .= (($perms & 0x0008) ?
		            (($perms & 0x0400) ? 's' : 'x' ) :
		            (($perms & 0x0400) ? 'S' : '-'));

		// World
		$info .= (($perms & 0x0004) ? 'r' : '-');
		$info .= (($perms & 0x0002) ? 'w' : '-');
		$info .= (($perms & 0x0001) ?
		            (($perms & 0x0200) ? 't' : 'x' ) :
		            (($perms & 0x0200) ? 'T' : '-'));

		return $info;
	}
}